package demo.database.H2.D02_性能测试;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.titan.core.utils.data.AssertUtils;
import com.titan.core.utils.data.RandomUtils;
import com.titan.core.utils.db.DBUtils;
import com.titan.core.utils.debug.Timer;

import demo.database.H2.utils.H2Utils;

public class T02_查询性能测试 {
    private static void run() throws Exception {
        run(1);         // [55毫秒] [用时(ms)=55]
//        run(10);        // [286毫秒] [用时(ms)=286]
//        run(100);       // [2秒144毫秒] [用时(ms)=2144]
//        run(1000);      // [16秒490毫秒] [用时(ms)=16490]
    }


    private static void run(int countTest) throws Exception {
        int rows = 100000;
        
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = H2Utils.getConnection();
            
            Timer timer = Timer.$();
            DBUtils.execute(conn, "CREATE TABLE cc (id varchar(40) PRIMARY KEY, data varchar(40), create_dt datetime)");
            stmt = conn.prepareStatement("INSERT INTO cc VALUES (RANDOM_UUID(), ?, NOW())");
            for(int i = 0; i < rows; i++){
                stmt.setString(1, Integer.toString(i));
                stmt.execute();
            }
            timer.print("H2插入"+rows+"次用时");
            
            run(conn, rows, countTest);
        } finally {
            DBUtils.close(stmt);
            DBUtils.close(conn);
        }
        
    }
    private static void run(Connection conn, int rows, int countTest) throws Exception {
        String[] poses = new String[countTest];
        for (int i = 0; i < countTest; i++) {
            int pos = RandomUtils.random(0, rows-1);
            poses[i] = Integer.toString(pos);
        }
        
        Timer timer = Timer.$();
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement("select data from cc where data=?");
            for (int i = 0; i < poses.length; i++) {
                ResultSet rest = null;
                try {
                    stmt.setString(1, poses[i]);
                    rest = stmt.executeQuery();
                    String value = null;
                    if (rest.next()) {
                        value =rest.getString(1);
                    }
                    AssertUtils.assertEquals(poses[i], value);
                } finally {
                    DBUtils.close(rest);
                }
            }
        } finally {
            DBUtils.close(stmt);
        }
        timer.print("H2查询"+countTest+"次用时");
    }
    

    
    public static void main(String[] args) {
        Timer timer = Timer.$();
        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            timer.print();
        }
    }
}
